Binarycrossentropygrad

计算二元交叉熵损失函数的梯度。

\[dx_n = dL'_n \cdot w_n \cdot \frac{x_n - y_n}{x_n(1 - x_n) + \epsilon}\]

其中 \(x_n\) 是前向预测值, \(y_n\) 是目标值, \(w_n\) 是样本权重, \(dL'_n\) 是上游梯度。reduction 参数决定了 \(dL'_n\) 的广播方式。

输入:
  • input_size - 输入张量的总元素数量。

  • reduction - 前向传播时使用的规约类型 (0: None, 1: Mean, 2: Sum)。

  • input_x - 前向传播时的预测值张量。

  • input_y - 前向传播时的目标值(标签)张量。

  • weight - (可选) 前向传播时使用的权重张量。

  • dloss - 来自后一层的上游梯度。

  • dx - (输出) 梯度结果的存储地址。

  • weight_defined - 权重是否有效的标志。若为非0,则`weight`参数必须提供。

  • core_mask - 核掩码。

输出:
  • dx - 写入计算出的对 input_x 的梯度。

支持平台:

FT78NE MT7004

备注

  • FT78NE 支持fp32

  • MT7004 支持fp16, fp32

共享存储版本:

void fp_binarycrossentropygrad_s(int input_size, int reduction, float *input_x, float *input_y, float *weight, float *dloss, float *dx, int weight_defined, int core_mask)
void hp_binarycrossentropygrad_s(int input_size, int reduction, half *input_x, half *input_y, half *weight, half *dloss, half *dx, int weight_defined, int core_mask)

C调用示例:

 1//FT78NE示例
 2#include <stdio.h>
 3#include <binarycrossentropygrad.h>
 4int main(int argc, char* argv[]) {
 5    float *input_x = (float *)0xA0000000;    // forward input_x, DDR
 6    float *input_y = (float *)0xB0000000;    // forward input_y
 7    float *weight = (float *)0xC0000000;     // forward weight
 8    float *dloss = (float *)0xD0000000;      // upstream gradient
 9    float *dx = (float *)0xE0000000;         // output gradient dx
10
11    int input_size = 1024;
12    int reduction = 1; // Mean
13    int weight_defined = 1; // true
14    int core_mask = 0xff;
15
16    fp_binarycrossentropygrad_s(input_size, reduction, input_x, input_y, weight, dloss, dx, weight_defined, core_mask);
17    return 0;
18}

私有存储版本:

void fp_binarycrossentropygrad_p(int input_size, int reduction, float *input_x, float *input_y, float *weight, float *dloss, float *dx, int weight_defined)
void hp_binarycrossentropygrad_p(int input_size, int reduction, half *input_x, half *input_y, half *weight, half *dloss, half *dx, int weight_defined)

C调用示例:

 1//FT78NE示例
 2#include <stdio.h>
 3
 4int main(int argc, char* argv[]) {
 5    float *input_x = (float *)0x10000000;    // forward input_x, L2
 6    float *input_y = (float *)0x11000000;    // forward input_y
 7    float *weight = (float *)0x12000000;     // forward weight
 8    float *dloss = (float *)0x13000000;      // upstream gradient
 9    float *dx = (float *)0x14000000;         // output gradient dx
10
11    int input_size = 1024;
12    int reduction = 1; // Mean
13    int weight_defined = 0; // false
14
15    fp_binarycrossentropygrad_p(input_size, reduction, input_x, input_y, weight, dloss, dx, weight_defined);
16    return 0;
17}